import { NextResponse } from 'next/server';
import { supabase } from '@/controller/supabase';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const projectId = searchParams.get('projectId');

  if (!projectId) {
    return NextResponse.json({
      success: false,
      error: true,
      message: '缺少项目ID参数',
      data: null
    }, { status: 400 });
  }

  try {
    await supabase
      .from('tasks')
      .update({
        task_type: 'search',
        update_time: new Date().toISOString(),
      })
      .eq('project_id', projectId)
      .select()
      .single();
    const insertResult = async () => {
      await supabase
        .from('results')
        .insert([
          {
            project_id: projectId,
            creator_id: '1e1c32dd-c713-4c8e-bd05-e5330f6fbd76',
            post_id: '8545ba48-c62c-4a1e-8b8b-6895575fb7d5',
            is_deleted: false,
            search_result: { "User": "lee", "Content": "内容testtest", "keyword": ["人工智能", "新能源汽车"], "platform": "tiktok" },
            match_score: { "规则1 AI相关的文章": "相关度 90%", "规则2 发布99条AI文章": "相关度 20%", "规则3 点赞数大于300": "相关度 50%" },
            user_verdict: "PENDING",
            create_time: new Date().toISOString(),
            update_time: new Date().toISOString()
          }
        ])
        .select()
        .single();
    }

    // 执行数据操作
    await insertResult();
    // 模拟API处理延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    await insertResult();

    return NextResponse.json({
      success: true,
      data: {
        keywords: [],
        criteria: []
      },
      message: 'AI分析完成'
    });
  } catch (error) {
    console.error('AI处理错误:', error);
    return NextResponse.json({
      success: false,
      error: true,
      message: '处理请求时出错',
      data: null
    }, { status: 500 });
  }
}